package com.diamondparking.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.TemporalType;
import org.apache.commons.lang.StringUtils;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.framework.EntityController;

@Stateful
@Name("reportManager")
@Scope(ScopeType.SESSION)
public class ReportManagerBean extends EntityController implements ReportManager {
    
    private Date beginDate;
    private Date endDate;

    public Date getBeginDate() {
        return beginDate;
    }

    public void setBeginDate(Date beginDate) {
        this.beginDate = beginDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }
    
    public String getReportUrl() {
        String url = "http://chart.apis.google.com/chart?cht=lc&chtt=Claims+Entered+Per+Day&amp;chs=400x400&amp;chd=t:%s";
        return String.format(url, StringUtils.join(getReport(), ','));
    }
    
    public List<Long> getReport() {
        if (beginDate == null || endDate == null) {
            return Collections.EMPTY_LIST;
        }
        
        Calendar c1 = Calendar.getInstance();
        c1.setTime(beginDate);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(endDate);
        
        return getReport(c1, c2);
    }
    
    public List<Long> getReport(Calendar begin, Calendar end){
        ArrayList<Long> store = new ArrayList<Long>();
        
        while(begin.before(end)){
            Calendar next = Calendar.getInstance();
            next.setTime(begin.getTime());
            next.add(Calendar.DAY_OF_MONTH, 1);
            
            System.out.println("begin:");
            System.out.println(begin);
            System.out.println("next:");
            System.out.println(next);
            
            String query = "SELECT COUNT(c) from Claim c WHERE :day <= c.entered and c.entered <= :next";
            Long count = (Long) createQuery(query)
                    .setParameter("day", begin, TemporalType.TIMESTAMP)
                    .setParameter("next", next, TemporalType.TIMESTAMP)
                    .getSingleResult();
            store.add(count);
            
            begin.add(Calendar.DAY_OF_MONTH, 1);
        }
        return store;
    }
    
    @Destroy
    @Remove
    public void destroy() {
    }
}
